package com.example.openim.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;

/**
 * @description:
 * @author: zyc
 * @created: 2024-06-26 11:19
 */
@Component
@Slf4j
public class Md5Utils {

    /**
     * 生成32位小写MD5
     *
     * @param plainText
     * @return
     */
    public String lowMD5_32(String plainText) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md5.digest(plainText.getBytes());
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            plainText = hexValue.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return plainText;
    }

    /**
     * 生成32位大写MD5
     *
     * @param plainText
     * @return
     */
    public String bigMD5_32(String plainText) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md5.digest(plainText.getBytes());
            StringBuffer hexValue = new StringBuffer();
            for(byte b : md5Bytes){
                hexValue.append(String.format("%02X",b));
            }
            plainText = hexValue.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return plainText;
    }

}
